package com.sicilin.object.action;

import com.sicilin.common.ajax.vo.AjaxResponse;
import com.sicilin.common.exception.BusinessException;
import com.sicilin.common.tree.TreeObject;
import com.sicilin.object.dto.ObjectDTO;
import com.sicilin.object.enums.ObjectTypeEnum;
import com.sicilin.object.service.ObjectService;
import com.sicilin.object.util.ObjectUtils;
import com.sicilin.object.vo.ObjectVO;
import com.sicilin.po.TCObject;
import com.sicilin.system.login.dto.LoginUser;
import com.sicilin.system.login.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by sicilin on 2017/7/31.
 */
@Controller
@RequestMapping("/objectAction")
public class ObjectAction {
    private static Logger logger = Logger.getLogger(ObjectAction.class);

    @Autowired
    private ObjectService objectService;

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/findByTree.json")
    @ResponseBody
    @RequiresPermissions({"object:object:search","admin"})
    public List<TreeObject<TCObject>> findObjectTree(
            @RequestParam(value = "id",required = false) Integer objectId,
            @RequestParam(value = "parentId",required = false) Integer parentId)throws Exception{
        List<TCObject> tcObjects = new ArrayList<TCObject>();
        if(objectId != null && objectId != 0){//展开一个节点
            tcObjects.addAll(objectService.findbyAsyncTree(objectId,60,1));
        }else if(parentId!= null && parentId != 0){//根目录建立
            TCObject rootNode = objectService.findTCObjectById(parentId);
            rootNode.setHasChildren(1);
            tcObjects.add(rootNode);
        }
        //将数据切换成页面树形用的对象
        List<TreeObject<TCObject>> treeObjects = ObjectUtils.changeToTreeObject(tcObjects);
        return treeObjects;
    }

    @RequestMapping(value = "/saveObject.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("object:object:save")
    public AjaxResponse saveObject(@RequestBody ObjectVO vo)throws Exception{
        Integer parentId = vo.getParentId();
        String objectCode = vo.getObjectCode();
        String objectName = vo.getObjectName();
        Boolean folder = vo.getFolder();
        if(folder == null){throw new BusinessException("请确定添加的是否为文件夹！");}
        if(parentId == 0){throw new BusinessException("不能添加最高类别（即最高父级）的同辈对象！");}
        if(StringUtils.isBlank(objectCode) || StringUtils.isBlank(objectName)){throw new BusinessException("编码或名称为空，不合法!");}
        LoginUser user = loginService.getCurrentUser();
        TCObject object = null;
        if(folder){
            object = objectService.saveObjectSonType(objectCode,objectName,parentId,1,user.getCompanyId(),ObjectTypeEnum.FOLDER);
        }else {
            object = objectService.saveObjectSonType(objectCode, objectName, parentId, 1, user.getCompanyId(), ObjectTypeEnum.SON);
        }
        return new AjaxResponse(object);
    }

    @RequestMapping(value = "/updateObject.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("object:object:update")
    public AjaxResponse updateObject(@RequestBody ObjectVO vo)throws Exception{
        Integer objectId = vo.getObjectId();
        String objectCode = vo.getObjectCode();
        String objectName = vo.getObjectName();
        if(StringUtils.isBlank(objectCode) || StringUtils.isBlank(objectName)){throw new BusinessException("编码或名称为空，不合法!");}
        TCObject object = objectService.updateTCObjectByidWidthType(objectId,objectCode,objectName,null,ObjectTypeEnum.NONE);
        return new AjaxResponse(object);
    }


    @RequestMapping(value = "/searchObjectType.json")
    @ResponseBody
    @RequiresPermissions("object:object:search")
    public List<TCObject> searchObjectType(@RequestParam("text") String text) throws Exception{
        List<TCObject> objectList = objectService.searchObjectFatherType(text);
        return objectList;
    }

    @RequestMapping(value = "/saveType.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"object:object:save","admin"})
    public AjaxResponse saveType(@RequestParam("objectCode") String objectCode,@RequestParam("objectName") String objectName,HttpServletResponse response) throws Exception{
        AjaxResponse vo = new AjaxResponse(objectService.saveObjectFatherType(objectCode,objectName,1));
        return vo;
    }

    @RequestMapping(value = "/updateType.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"object:object:save","admin"})
    public AjaxResponse updateType(@RequestParam("objectId") int objectId,
                                   @RequestParam("objectCode") String objectCode,
                                   @RequestParam("objectName") String objectName) throws Exception{
        AjaxResponse vo = new AjaxResponse(objectService.updateTCObjectByidWidthType(objectId,objectCode,objectName,null, ObjectTypeEnum.FATHER));
        return vo;
    }

    @RequestMapping(value = "/searchObjectWithTree.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("object:object:search")
    public List<TreeObject<ObjectDTO>> searchObjectWithTree(
            @RequestParam(value = "search",required = false) String search
            ,@RequestParam(value = "totalCodes[]") List<String> totalCodes
            ,@RequestParam(value = "id",required = false) Integer objectId
    ) throws Exception{
        LoginUser user = loginService.getCurrentUser();
        int companyId = user.getCompanyId();
        List<ObjectDTO> tcObjects = null;
        if(objectId == null){
            tcObjects = objectService.searchObjectTreeWidthCompanyId(search,totalCodes,companyId);
        }else {
            tcObjects = objectService.searchObjectTreeByParentIdWidthCompanyId(objectId,companyId);
        }
        List<TreeObject<ObjectDTO>> result = ObjectUtils.changeToTreeObjectDTO(tcObjects);
        return result;
    }

    @RequestMapping(value = "/findObjectByCodes.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("object:object:search")
    public AjaxResponse findObjectByCodes(@RequestBody Set<String> objectCodes)throws Exception{
        LoginUser user = loginService.getCurrentUser();
        List<TCObject> objects = objectService.findObjectByCodes(objectCodes,user.getCompanyId());
        return new AjaxResponse(objects);
    }

}
